-- lua
-- coroutines is difficult
-- pattern:
-- 把action包裹coroutine.wrap(含create和resume)
-- 在action实现挂起(包含yield)
-- Logic: 
-- for table {1,2,3,4,5}
-- switch 1 and 5, list all combination of 2,3,4,5
-- 2345-1
-- 3452-1
-- 4523-1
-- 5234-1
-- 345-12
-- 453-12
-- 534-12
-- switch back 5 and 4



local a = {"a","b","c"}

function action(a,n)
    if n == 0 then
        coroutine.yield(a)
    end
    for i=1,n do
        a[i],a[n] = a[n],a[i]
        action(a,n-1)
        a[n],a[i] = a[i],a[n]
    end
end

function factory(a)
    local n = table.getn(a)
    return coroutine.wrap(function()
        action(a, n)
    end)
    -- local co = coroutine.create(function()
    --     perm(a, n)
    -- end)
    -- return function( ... )
    --     local code,result = coroutine.resume(co)
    --     return result
    -- end
end


function print_result( a )
    for i,v in ipairs(a) do
        io.write(v," ")
    end
    io.write("\n")
    -- body
end

local x = factory(a)
print(x)

for p in x do
    print_result(p)
end
